package com.moly.grpc.nio;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

public class FileServer {
    public static void main(String[] args) {

        FileServer fileServer = new FileServer();
        fileServer.init();
        fileServer.listen();
    }

    private ServerSocketChannel serverSocketChannel = null;
    private Selector selector = null;


    public void handle(SelectionKey next) {

        if (next.isAcceptable()) {
            ServerSocketChannel channel = (ServerSocketChannel) next.channel();
            SocketChannel accept = null;
            try {
                accept = channel.accept();
                regisetrChannel(selector, accept, SelectionKey.OP_READ);
                if (accept.isConnected()) {
                    accept.write(ByteBuffer.wrap("success link".getBytes(Charset.forName("utf-8"))));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if (next.isReadable()) {
            SocketChannel channel = (SocketChannel) next.channel();
            regisetrChannel(selector, channel, SelectionKey.OP_WRITE|SelectionKey.OP_READ);
//            regisetrChannel(selector, channel, SelectionKey.OP_READ);
            try {
                ByteBuffer byteBuffer = ByteBuffer.allocate(100);
                int len = 0;
                String s = "";

                    while ((len = channel.read(byteBuffer)) > 0) {
                        byteBuffer.flip();

                        s += new String(byteBuffer.array(), 0, len,Charset.forName("utf-8"));
                        byteBuffer.clear();
                    }
                    if (len < 0) {
                        System.out.println(" 客户端异常");
                        channel.close();
                        return;
                    }
                    if(len==0){
                        System.out.println("客户发送 :"+s);
                    }




            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        if (next.isWritable()) {
            SocketChannel channel = (SocketChannel) next.channel();
            try {


                System.out.println("请输入");
                InputStreamReader inputStreamReader = new InputStreamReader(System.in);
                char[] c = new char[1024];
                int read = inputStreamReader.read(c);
                String s = new String(c, 0, read);
                s = "\n\r" + s + "\n\r";
                channel.write(ByteBuffer.wrap(s.getBytes(Charset.forName("utf-8"))));
                regisetrChannel(selector, channel, SelectionKey.OP_READ);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public void regisetrChannel(Selector selector, SelectableChannel channel, int ops) {
        try {
            channel.configureBlocking(false);
            channel.register(selector, ops);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void listen() {
        while (true) {

            try {
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {

                    SelectionKey next = iterator.next();
                    handle(next);
                    iterator.remove();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public void init() {
        try {
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.socket().bind(new InetSocketAddress(8899));

            selector = Selector.open();
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
